package com.example.lenovo.asia5b.home.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.lenovo.asia5b.commodity.activity.ServiceActivity;
import com.example.lenovo.asia5b.home.bean.MyDataBean;
import com.example.lenovo.asia5b.home.bean.UserBean;
import com.example.lenovo.asia5b.my.activity.MessageActivity;
import com.example.lenovo.asia5b.my.activity.MyCollectActivity;
import com.example.lenovo.asia5b.my.activity.MyDataActivity;
import com.example.lenovo.asia5b.my.activity.MyHistoryActivity;
import com.example.lenovo.asia5b.my.activity.MyWalletDetailActivity;
import com.example.lenovo.asia5b.my.activity.SettingActivity;
import com.example.lenovo.asia5b.my.order.activity.TheOrderActvity;
import com.example.lenovo.asia5b.ui.CircleImageView;
import com.example.lenovo.asia5b.ui.DownloadPicture;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.MoneyUtil;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPrefereLoginUtils;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import app.BaseFragment;

import static android.app.Activity.RESULT_OK;
import static com.example.lenovo.asia5b.home.fragment.MianHomeFragment.message_count;
import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;


/**
 * 我的
 *
 * Created by lenovo on 2017/6/20.
 */

public class MianMyA5bFragment extends BaseFragment implements View.OnClickListener, ICallBack, MoneyUtil.MoneyInterface {

    public View fragmentView;
    private LinearLayout ll_my_wallet,ll_the_order,ll_message,ll_setting,ll_kefu,ll_background,ll_my_collect,ll_my_history;
    private CircleImageView image_head;

    private TextView a5b_username,a5b_integral,a5b_account_details;
    private   MoneyUtil moneyUtil = null;
    private static  ImageView img_mess;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.frame_main_my_a5b, container,false);
        initView();
        myInfoData();
        return fragmentView;
    }

    public void initView() {
        moneyUtil= new MoneyUtil(this);
        ll_my_wallet = (LinearLayout)fragmentView.findViewById(R.id.ll_my_wallet);
        ll_the_order = (LinearLayout)fragmentView.findViewById(R.id.ll_the_order);
        ll_message = (LinearLayout)fragmentView.findViewById(R.id.ll_message);
        ll_setting = (LinearLayout)fragmentView.findViewById(R.id.ll_setting);
        ll_kefu = (LinearLayout)fragmentView.findViewById(R.id.ll_kefu);
        ll_my_collect = (LinearLayout)fragmentView.findViewById(R.id.ll_my_collect);
        ll_my_history= (LinearLayout)fragmentView.findViewById(R.id.ll_my_history);
        image_head = (CircleImageView)fragmentView.findViewById(R.id.image_head);
        img_mess  =(ImageView)fragmentView.findViewById(R.id.img_mess);
        initUserInfo();


        ll_my_wallet.setOnClickListener(this);
        ll_the_order.setOnClickListener(this);
        ll_message.setOnClickListener(this);
        ll_setting.setOnClickListener(this);
        ll_kefu.setOnClickListener(this);
        ll_my_collect.setOnClickListener(this);
        ll_my_history.setOnClickListener(this);

        ll_background = fragmentView.findViewById(R.id.ll_background);

        image_head.setOnClickListener(this);

//        String dd = "http://img.my.csdn.net/uploads/201410/19/1413698867_8323.jpg";
//        ImageLoader.getInstance().displayImage(dd, image_head, new SimpleImageLoadingListener() {
//            //刚加载
//            @Override
//            public void onLoadingStarted(String imageUri, View view) {
//            }
//            //加载失败
//            @Override
//            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
//            }
//            //加载完成
//            @Override
//            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//                Bitmap newBitmap =  StackBlur.blurNativelyPixels(loadedImage, 30, false);
//                BitmapDrawable drawable = new BitmapDrawable(newBitmap);
//                ll_background.setBackground(drawable);
//            }
//        });
    }

    /**
     * 消息数量
     */
    @Override
    public void onStart() {
        super.onStart();
        if (message_count == 0) {
            img_mess.setVisibility(View.GONE);
        } else {
            img_mess.setVisibility(View.VISIBLE);
        }
    }

    public static  void setMessCount(int id) {
        if (null != img_mess) {
            if (id == 0){
                img_mess.setVisibility(View.GONE);
            } else {
                img_mess.setVisibility(View.VISIBLE);
            }
        }
    }

    private void initUserInfo(){
        UserBean userBean = (UserBean) SharedPreferencesUtils.getObjectFromShare("user");
        if (null == userBean) {
            return;
        }
        DownloadPicture.loadHearNetwork(userBean.avatar,image_head);

        //用户名
        a5b_username = (TextView)fragmentView.findViewById(R.id.a5b_username);
        a5b_username.setText(userBean.user_name);
        //积分
        a5b_integral = (TextView)fragmentView.findViewById(R.id.a5b_integral);
        a5b_integral.setText("："+userBean.pay_points);
        //账户余额
        a5b_account_details = (TextView)fragmentView.findViewById(R.id.a5b_account_details);
        a5b_account_details.setText("："+userBean.user_money);
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
		case R.id.ll_my_wallet:
            intent = new Intent(getActivity(), MyWalletDetailActivity.class);
            startActivity(intent);
		    break;
            case R.id.ll_the_order:
                intent = new Intent(getActivity(), TheOrderActvity.class);
                startActivity(intent);
                break;
            case R.id.ll_message:
                intent = new Intent(getActivity(), MessageActivity.class);
                img_mess.setVisibility(View.GONE);
                message_count = 0;
                SharedPreferencesUtils.setInt("Message_Count",message_count);
                startActivity(intent);
                break;
            case R.id.ll_setting:
                intent = new Intent(getActivity(), SettingActivity.class);
                startActivityForResult(intent, Activity.RESULT_FIRST_USER);
                break;
            case R.id.ll_kefu:
//                intent = new Intent(getActivity(), CustomerServiceActivity.class);
                intent = new Intent(getActivity(), ServiceActivity.class);
                startActivity(intent);
                break;
            case R.id.image_head:
                intent = new Intent(getActivity(), MyDataActivity.class);
                startActivityForResult(intent, Activity.RESULT_FIRST_USER);
                break;
            case R.id.ll_my_collect:
                intent = new Intent(getActivity(), MyCollectActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_my_history:
                intent = new Intent(getActivity(), MyHistoryActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }


    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        switch(resultCode){
            //当用户修改头像就到这里来
            case RESULT_OK:
//                UserBean userBean = SharedPreferencesUtils.getUserBean();
//                DownloadPicture.loadHearNetwork(userBean.avatar,image_head);
//                a5b_username.setText(userBean.nickname);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //刷新用户余额
        if (null != a5b_account_details) {
            moneyUtil.moneyData();
        }
        UserBean userBean = getUserBean();
        if (null !=userBean) {
            if (null != a5b_username) {
                DownloadPicture.loadHearNetwork(userBean.avatar, image_head);
                a5b_username.setText(userBean.user_name);
            }
        }
        SharedPrefereLoginUtils.setBeanList(userBean);
    }
    @Override
    public void money(String user_money,String pay_points) {
        a5b_account_details.setText("："+user_money);
        a5b_integral.setText("："+pay_points);
    }

    /**
     * 获取个人资料接口
     */
    public void myInfoData() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.MY_INF0;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 1);
        }catch (Exception e) {

        }
    }


    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;

            if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONObject user_info = json.getJSONObject("user_info");
                            MyDataBean bean = (MyDataBean) Logic.getBeanToJSONObject(user_info, new MyDataBean());

                            UserBean bean2 = getUserBean();
                            if (null == bean2){
                                return;
                            }
                            bean2.mobile_phone = bean.mobile_phone;
                            SharedPreferencesUtils.setObjectToShare(bean2, "user");
                        }
                    }catch (Exception e) {

                    }
                } else {
//                U.Toast(MyDataActivity.this, "调用失败");
                }
            }
        }
    };
}
